import tkinter as tk
from tkinter import messagebox
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter import filedialog
import openpyxl
import re
from openpyxl.styles import PatternFill
import os

class AppWindow(ttk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.title = '霹雳无敌二字人名全角空格横通裂空融合升级工具'
        self.initUI()

    def initUI(self):
        self.master.title(self.title)
        self.master.geometry('450x450')  # 增加窗口高度

        # 文件选择标签和按钮
        self.file_label = ttk.Label(self.master, text='选择的文件: 无')
        self.file_label.pack(pady=5)
        self.file_button = ttk.Button(self.master, text='选择Excel文件', command=self.openFileNameDialog)
        self.file_button.pack(pady=5)

        # 删除制表符的勾选框
        self.remove_tabs_var = ttk.BooleanVar(value=True)
        ttk.Checkbutton(self.master, text="删除制表符", variable=self.remove_tabs_var).pack(pady=5)

        # 空一行
        ttk.Label(self.master, text="").pack()

        # 添加全角空格的勾选框
        self.add_space_var = ttk.BooleanVar(value=True)
        ttk.Checkbutton(self.master, text="添加全角空格", variable=self.add_space_var).pack(pady=5)

        # 文件保存方式选择
        self.saveChoice = ttk.IntVar(value=1)  # 默认生成新文件
        ttk.Radiobutton(self.master, text="生成新文件", variable=self.saveChoice, value=1).pack(pady=5)
        ttk.Radiobutton(self.master, text="覆盖原文件", variable=self.saveChoice, value=2).pack(pady=5)

        # 空一行
        ttk.Label(self.master, text="").pack()

        # 修改字号的勾选框
        self.change_font_var = ttk.BooleanVar(value=True)
        ttk.Checkbutton(self.master, text="修改字号", variable=self.change_font_var).pack(pady=5)

        # 字号输入
        self.chinese_font_size_label = ttk.Label(self.master, text='输入中文字号:')
        self.chinese_font_size_label.pack(pady=5)
        self.chinese_font_size_entry = ttk.Entry(self.master)
        self.chinese_font_size_entry.pack(pady=5)
        self.english_font_size_label = ttk.Label(self.master, text='输入英文字号:')
        self.english_font_size_label.pack(pady=5)
        self.english_font_size_entry = ttk.Entry(self.master)
        self.english_font_size_entry.pack(pady=5)

        # 开始处理按钮
        self.start_button = ttk.Button(self.master, text='开始处理', command=self.processWorkbook)
        self.start_button.pack(pady=10)

    def openFileNameDialog(self):
        self.fileName = filedialog.askopenfilename(title="选择Excel文件",
                                                   filetypes=(("Excel files", "*.xlsx"), ("all files", "*.*")))
        if self.fileName:
            self.file_label.config(text=f'选择的文件: {self.fileName}')

    def processWorkbook(self):
        if self.fileName:
            chinese_size = self.chinese_font_size_entry.get()
            english_size = self.english_font_size_entry.get()
            chinese_size = float(chinese_size) if chinese_size else None
            english_size = float(english_size) if english_size else None

            workbook = openpyxl.load_workbook(self.fileName)

            if self.remove_tabs_var.get():
                remove_tabs_from_all_sheets(workbook)

            if self.add_space_var.get():
                add_full_width_space_to_all_sheets(workbook)

            if self.change_font_var.get():
                apply_font_styles(workbook, chinese_size, english_size)

            if self.saveChoice.get() == 1:
                base_name, extension = os.path.splitext(self.fileName)
                new_file_name = f"{base_name}_modified{extension}"
                workbook.save(new_file_name)
            else:
                workbook.save(self.fileName)

            workbook.close()
            self.file_label.config(text='选择的文件: 无')
            messagebox.showinfo('处理结果', '文件处理完成')
        else:
            messagebox.showinfo('错误', '没有选择文件')


def apply_font_styles(workbook, chinese_font_size, english_font_size):
    for sheet in workbook.worksheets:
        for row in sheet.iter_rows():
            for cell in row:
                if cell.value and isinstance(cell.value, str):
                    if re.search('[\u4e00-\u9fff]', cell.value):
                        if chinese_font_size is not None:
                            cell.font = Font(size=chinese_font_size, color=cell.font.color)
                    else:
                        if english_font_size is not None:
                            cell.font = Font(size=english_font_size, color=cell.font.color)


def add_full_width_space_to_all_sheets(workbook):
    for sheet in workbook.sheetnames:
        sheet = workbook[sheet]
        for row in sheet.iter_rows(min_row=1, max_col=sheet.max_column, max_row=sheet.max_row, values_only=False):
            for cell in row:
                if cell.value is not None and len(cell.value) == 2:
                    if all('\u4e00' <= c <= '\u9fff' for c in cell.value):
                        cell.value = cell.value[0] + '　' + cell.value[1]

    # 保留单元格的背景颜色
    for sheet in workbook.worksheets:
        for row in sheet.iter_rows():
            for cell in row:
                if cell.fill is not None:
                    fill = PatternFill(fill_type=cell.fill.fill_type, fgColor=cell.fill.fgColor,
                                       bgColor=cell.fill.bgColor)
                    cell.fill = fill


def remove_tabs_from_all_sheets(workbook):
    for sheet in workbook.worksheets:
        for row in sheet.iter_rows():
            for cell in row:
                if cell.value and isinstance(cell.value, str):
                    if re.search('[\u4e00-\u9fff]', cell.value):
                        cell.value = re.sub(r'\s+', '', cell.value)


if __name__ == '__main__':
    root = ttk.Window(themename="darkly")  # 修改主题名称为 "darkly"
    app = AppWindow(root)
    app.pack(fill=BOTH, expand=True)
    root.mainloop()